import sys
import cv2


"""

本程序实现了，从一张图片中提取黄色像素的区域，即提取出输油管道，为后续从输油管道上漏油斑点的检测做准备

"""


class ImageViewer():
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        image_path = "oil_2.png"
        img = cv2.imread(image_path)
        img = cv2.resize(img, (640, 400))
        if img is not None:

            cv2.imshow("Step", img)
            cv2.waitKey(0)

            # 将图像从BGR转换到HSV
            hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

            # 定义黄色的HSV范围
            lower_yellow = (20, 100, 100)
            upper_yellow = (30, 255, 255)

            # 进行颜色阈值的二值化处理，得到黄色区域的掩码
            mask_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow)
            cv2.imshow("Step", mask_yellow)
            cv2.waitKey(0)

            # 查找黄色区域内的轮廓
            contours, _ = cv2.findContours(mask_yellow, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

            # 创建一个和原图像大小相同的全黑图像
            result = img.copy()
            result.fill(0)

            # 遍历轮廓，将轮廓内的区域从原图像复制到结果图像
            for contour in contours:
                x, y, w, h = cv2.boundingRect(contour)
                roi = img[y:y + h, x:x + w]
                result[y:y + h, x:x + w] = roi
            # 显示结果图像
            cv2.imshow("Step", result)
            cv2.waitKey(0)

if __name__ == '__main__':
    ex = ImageViewer()